//app.js
var util = require('./utils/util.js');
var dataParse = require('./utils/dataParse.js');
//var cloud = require('./utils/cloud.js');
var aliyun_api = require('./utils/aliyun-api-gateway.js');
const sMD5 = require('./utils/spark-md5.js');
let buffer;

App({
  buf2hex: function (buffer) {
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('')
  },
  buf2string: function (buffer) {
    var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
    var str = ''
    for (var i = 0; i < arr.length; i++) {
      str += String.fromCharCode(arr[i])
    }
    return str
  },
  onLaunch: function () {
    var that = this;
    // 展示本地存储能力
    that.globalData.BLE.bleData = new util.ByteArray()
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    this.globalData.SystemInfo = wx.getSystemInfoSync()
  
    wx.cloud.init()
  //  that.test1()
    /**回复报文 */
  //  that.MsgResp()



    // downloadTask.onProgressUpdate((res) => {
    //   console.log('下载进度', res.progress)
    //   console.log('已经下载的数据长度', res.totalBytesWritten)
    //   console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
    // })


    const downloadTask = wx.downloadFile({
      url: 'https://hik-smartlock-ota.oss-cn-shanghai.aliyuncs.com/sysfile.bin', //仅为示例，并非真实的资源
      success(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          console.log(res)
          wx.getFileSystemManager().readFile({
            filePath: res.tempFilePath, //选择图片返回的相对路径
            // encoding: 'base64', //编码格式
            success: res => { //成功的回调
              // console.log(res)
              // console.log(res.data)

              // console.log(res.data.byteLength)
              buffer = new ArrayBuffer(res.data.byteLength)
              buffer = res.data.slice(0)
              // console.log(buffer)

              var spark = new sMD5.ArrayBuffer();   //计算MD5
              spark.append(buffer.slice(0, -20));
              var calcCheck = spark.end(false);

              // var div = that.buf2hex(buffer).slice(-40, -32)
              var receCheck = that.buf2hex(buffer).slice(-32)

              // console.log(div)
              // console.log(receCheck)
              // console.log(calcCheck)

              if (receCheck == calcCheck) {                //校验正确 
                let buf = buffer.slice(0,-20)
                // console.log(buf)
                // console.log(that.buf2hex(buf))
                that.globalData.upgradeData = buf
                that.globalData.latestVersion = that.globalData.latestVersion
              }
              else {
                console.log("download error!")
              }
            },
            fail: res => {
              console.log(res)
            }
          })
        }
      }
    })
    

  },
  globalData: {
    deviceInfo:{
      LockState:'-',
      BatteryPercentage:0,
      SN:'-',
      Volume: 0,
    },
    kvStorage: [],
    accountInfo: null,
    userInfo: null,
    SystemInfo: {},
    BLE: {
      deviceName: null,
      devicesList: [],
      connectedDevice: [],
      connectedDeviceId: '',
      services: [],
      servicesId: [],
      characteristics: [],
      characteristicsId: [],
      connected: false,
      bleData: null
    },
    bletype:0,//0：蓝牙开锁  1：临时密码蓝牙开锁  2：OTA升级请求  3：OTA升级数据  4：OTA升级完成
    latestVersion:'1.0.0',
    upgradeData:null,
    upgradeProgress:0,
    stopUpgrade:false
    /*
    deviceInfo: [{
      usedNum: 0,
      totalNum: 20,
      detailInfo: []
    }, {
      usedNum: 0,
      totalNum: 100,
      detailInfo: []
    }, {
      usedNum: 0,
      totalNum: 100,
      detailInfo: []
    },]*/
  },
})